

cc.Class({
    extends: cc.Component,

    properties: {
        //排行榜的父节点.
        rankDisplayNode:{
            default: null,
            type: cc.Node
        },
        //存放排行榜子物体的框.
        content:{
            default: null,
            type: cc.Node
        },
        RankItem: cc.Prefab,
        highScoreLabel: {
            default: null,
            type: cc.Label
        },
        selfInfoNode:{
            default: null,
            type: cc.Node
        },
        startPanel:cc.Node,
        gamePanel:cc.Node,
        //后来写的，不分模块了
        newScoreNode: cc.Node
    },

    // LIFE-CYCLE CALLBACKS:

    onLoad () {
        // 适配解决方案
        let _canvas = cc.Canvas.instance;
        // 设计分辨率比
        let _rateR = _canvas.designResolution.height/_canvas.designResolution.width;
        // 显示分辨率比
        let _rateV = cc.director.getVisibleSize().height/cc.director.getVisibleSize().width;
        console.log("winSize: _rateR: "+_rateR+" rateV: "+_rateV);
        if (_rateV > _rateR) 
        {
            _canvas.fitHeight = false;
            _canvas.fitWidth = true;
            console.log("winSize: fitWidth");
        }
        else
        {
            _canvas.fitHeight = true;
            _canvas.fitWidth = false;
            console.log("winSize: fitHeight");
        }
        this.selfName = "";
        this.selfHead = "";
        //本次进入存储的最高分数.
        this.selfScore = 0;
        //设置接收到消息的处理.
        wx.onMessage(data => {
            switch (data.message) {
                case 'ShowRank':
                    this.showRank();
                    break;
                case 'HideRank':
                    this.hideRank();
                    break;
                case 'SetHighScore':
                    this.uploadWXData(data.score);
                    break;
                case 'StartScene':
                    this.showStartScene();
                    break;
                case 'GameScene':
                    this.showGameScene();
                    break;
            }
        });       
        this.getSelfInfo();
        this.getSelfData();
    },

    start () {
    },

    showStartScene(){
        this.startPanel.active = true;
        this.gamePanel.active = false;
        this.newScoreNode.active = false;
    },

    showGameScene(){
        this.gamePanel.active = true;
        this.startPanel.active = false;
        this.newScoreNode.active = false;
    },

    // update (dt) {},

    //显示最高分数.
    showHighScore(score){
        this.highScoreLabel.string = score.toString();
    },

    //显示好友排行榜.
    showRank () {
        this.rankDisplayNode.active = true;
        this.friendRank();
    },

    //隐藏好友排行榜.
    hideRank () {
        this.rankDisplayNode.active = false;
        //删除所有的RankItem.
        var rankItems = this.content.children;
        for(var i = 0; i < rankItems.length; i++){
            rankItems[i].destroy();
        } 
        var selfItem = this.selfInfoNode.children;
        //应该只有一个.
        for(var i = 0; i < selfItem.length; i++){
            selfItem[i].destroy();
        } 
    },

    //获取玩家数据.
    getSelfInfo(){
        var self = this;
        //获取玩家的数据.
        wx.getUserInfo({
            openIdList: ['selfOpenId'],
            lang: 'zh_CN',
            success(res){
                if(res.data){
                    console.log(res.data);
                    if(res.data[0].nickName != undefined && res.data[0].avatarUrl != undefined){
                        self.selfName = res.data[0].nickName;
                    }
                    else{
                        console.log("自己的信息1:undefined");
                    }
                }                
            },
            fail(){
                //console.log(res)
                console.log("获取自己的信息失败");
            }
        });
    },

    //获得自己的游戏数据.
    getSelfData(){
        var self = this;
        wx.getUserCloudStorage({
            keyList: ["RotateJump_MaxScore"],
            success(res){
                console.log("自己的托管数据");
                if(res.KVDataList){
                    var dList = res.KVDataList;
                    console.log("自己的托管数据1:dList.length=" + dList.length);
                    for(var i = 0; i < dList.length; i++){
                        if(dList[i].key == "RotateJump_MaxScore"){
                            console.log("自己的托管数据1:" + dList[i].value);
                            self.selfScore = parseInt(dList[i].value);
                            //首次加载成功显示分数.
                            self.highScoreLabel.string = self.selfScore.toString();
                            break;
                        }
                    }
                }                
            },
            fail(){
                //console.log(res)
                console.log("获取自己的托管数据失败");
            }
        })
    },

    //上传数据到服务器.
    uploadWXData: function(bestHeight){ //上报到微信服务器：历史最高分
        //进行二判是否比服务器上的分数高.
        if(bestHeight <= this.selfScore){
            return;
        }
        console.log('上传最高分'+bestHeight);
        this.selfScore = bestHeight;
        var kvDataList = new Array();
        kvDataList.push({key:"RotateJump_MaxScore", value: "" + bestHeight});
        wx.setUserCloudStorage({ KVDataList: kvDataList })
        //显示最高分.
        this.showHighScore(this.selfScore);
        this.newScoreNode.active = true;
    },

    //好友排名实现.
    friendRank(){
        var self = this;
        wx.getFriendCloudStorage({
            keyList: ["RotateJump_MaxScore"],
            success(res){
                console.log(res);
                if(res.data){
                //self.tips.active = false;
                //按maxScore从大到小排列
                self.sortList(res.data, false); 
                //清掉.
                var rankItems = self.content.children;
                for(var i = 0; i < rankItems.length; i++){
                    rankItems[i].destroy();
                } 
                for(var i = 0; i < res.data.length; i++){
                    //给每一个玩家生成node节点.
                    var item = cc.instantiate(self.RankItem); 
                    item.parent = self.content;
                    item.getComponent("RankItem").initView(res.data[i], i, false);  
                } 
                //设置content长度.
                self.content.height = self.RankItem.data.height * res.data.length;
                console.log('content'+self.content.height);
                //获得自己对应的data索引
                var selfDataIndex = null;
                //先比较昵称
                var sameNameList = [];
                for(var i = 0; i < res.data.length; i++){
                    if(res.data[i].nickname == self.selfName){
                        sameNameList.push(i);
                    }
                }
                if(sameNameList.length < 1){
                    console.log("Rank:好友的信息1：未找到同名自己");
                }else if(sameNameList.length == 1){
                    console.log("Rank:好友的信息2：找到1个同名自己");
                    selfDataIndex = sameNameList[0];
                }else{
                    再比较头像
                    var sameHeadList = [];
                    for(var i = 0; i < sameNameList.length; i++){
                        if(res.data[i].avatarUrl == self.selfHead){
                            sameHeadList.push(i);
                        }
                    }
                    if(sameHeadList.length < 1){
                        console.log("Rank:好友的信息3：未找到同头像自己");
                    }else if(sameHeadList.length == 1){
                        selfDataIndex = sameHeadList[0];
                    }else{
                        //再比较最高积分
                        var sameMaxScoreList = [];
                        for(var i = 0; i < sameNameList.length; i++){
                            var dList = res.data[sameNameList[i]].KVDataList;
                            for(var j = 0; j < dList.length; j++){
                                if(dList[j].key == "RotateJump_MaxScore" && dList[j].value == self.selfScore){
                                    sameMaxScoreList.push(i);
                                }
                            }
                        }
                        if(sameMaxScoreList.length < 1){
                            console.log("Rank:好友的信息3：未找到同周最高积分自己");
                        }else if(sameMaxScoreList.length == 1){
                            selfDataIndex = sameMaxScoreList[0];
                        }else{ //到这里，发现多个同昵称、同头像、同最高积分的玩家，只能随机了
                            var value = Math.floor(Math.random() * (sameMaxScoreList.length - 1 + 1) + 1) - 1;
                            selfDataIndex = sameMaxScoreList[value - 1];
                        }
                    }
                }
                console.log("Rank:selfDataIndex=" + selfDataIndex);
                //设置自己的信息
                var item = cc.instantiate(self.RankItem); 
                item.parent = self.selfInfoNode;
                item.setPosition(cc.v2(0,0));
                item.getComponent("RankItem").initView(res.data[selfDataIndex], selfDataIndex, true);  
                }else{
                    //self.tips.active = true;
                }               
            },
            fail(){
                //console.log(res)
                console.log("Rank:获取好友的信息失败");
                //self.tips.active = true;
            }
        })
            
    },

    //排序(ListData：res.data;order:false降序，true升序)
    //保证不同用户的排行榜相同.
    sortList: function(ListData, order){ 
        ListData.sort(function(a,b){
        var AMaxScore = 0;
        var KVDataList = a.KVDataList;
        for(var i = 0;i < KVDataList.length;i++){
        if(KVDataList[i].key == "RotateJump_MaxScore"){
        AMaxScore = KVDataList[i].value;
        }
        }
        
        
        var BMaxScore = 0;
        KVDataList = b.KVDataList;
        for(var i = 0; i<KVDataList.length; i++){
        if(KVDataList[i].key == "RotateJump_MaxScore"){
        BMaxScore = KVDataList[i].value;
        }
        }
        
        
        if(order){
        return parseInt(AMaxScore) - parseInt(BMaxScore);
        }else{
        return parseInt(BMaxScore) - parseInt(AMaxScore);
        }
        });
        return ListData;
    },


});
